package com.sgb.kjwl.view.ui.activity.transport.company;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.viewpager2.widget.ViewPager2;

import com.sgb.alimaplibrary.util.ToastUtil;
import com.sgb.capital.utils.StringUtils;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityAffiliatedFleetDetailsBinding;
import com.sgb.kjwl.model.entity.transport.AffiliatedFDetailsListEntity;
import com.sgb.kjwl.model.entity.transport.SelfFleetEntity;
import com.sgb.kjwl.model.entity.transport.TabEntity;
import com.sgb.kjwl.view.constant.RouterKey;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.swgk.core.event.MenuEvent;
import com.sgb.kjwl.view.event.self.GoodsManageEvent;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.adapter.self.logistics.SimpleFragmentAdapter;
import com.sgb.kjwl.view.ui.adapter.transport.GreySimpleTabAdapter;
import com.sgb.kjwl.view.ui.fragment.transport.company.AffiliatedFDetailsFragment;
import com.sgb.kjwl.view.ui.fragment.transport.company.SelfSupportDetailsFragment;
import com.sgb.kjwl.view.widget.transport.AlignImageSpan;
import com.sgb.kjwl.viewmodel.transport.AffiliatedFDetailsModel;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * author:熊丽
 * createDate:2021/10/15 10:41
 * introduce:车队详情
 * modifier:xxx
 * modifiyDate:
 * modifiyContent:
 */
public class AffiliatedFleetDetailsActivity extends AppActivity {
    ActivityAffiliatedFleetDetailsBinding binding;
    AffiliatedFDetailsModel viewModel;
    //顶部tab 复用货源管理同一布局
    private GreySimpleTabAdapter tabAdapter;
    private List<TabEntity> mTabs;
    private final List<Fragment> mFragments = new ArrayList<>();
    private boolean isSelf = false;
    private String motorcadeNo ;
    AffiliatedFDetailsListEntity listResponse;
    //跳转操作
    public static void start(Context context, boolean isSelf,String motorcadeNo) {
        Intent intent = new Intent(context, AffiliatedFleetDetailsActivity.class);
        intent.putExtra(RouterKey.BOOLEAN, isSelf);
        intent.putExtra(RouterKey.STRING,motorcadeNo);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }
    @Override
    protected void init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        binding = DataBindingUtil.setContentView(this, R.layout.activity_affiliated_fleet_details);
        viewModel = new ViewModelProvider(this).get(AffiliatedFDetailsModel.class);
        binding.includeTitle.titleView.setText("车队详情");
        isSelf = getIntent().getBooleanExtra(RouterKey.BOOLEAN, false);
        motorcadeNo = getIntent().getStringExtra(RouterKey.STRING);
        viewModel.getAffiliatedFDetails(this,motorcadeNo,isSelf?1:2);
        viewModel.ldGoods.observe(this, this::refreshUIByData);
        viewModel.lddelete.observe(this,success->{
            if ("sucess".equals(success)){
                finish();
            }
        });
        viewModel.ldunbind.observe(this,success->{
            if ("sucess".equals(success)){
                viewModel.getAffiliatedFDetails(this,motorcadeNo,isSelf?1:2);
            }
        });
        initTab();
        initEvent();
    }
    private void initTab() {
        mTabs = new ArrayList<>();
        mTabs.add(new TabEntity(isSelf?"车队司机":"共享司机"));
        mTabs.add(new TabEntity(isSelf?"车队车辆":"共享车辆"));
        tabAdapter = new GreySimpleTabAdapter(mTabs);
        binding.rvTab.setLayoutManager(new GridLayoutManager(this,2));
        binding.rvTab.setAdapter(tabAdapter);
    }
    private void initEvent() {
        binding.tvAffDetailsIm.setOnClickListener(this);
        binding.tvAffDetailsCall.setOnClickListener(this);
        binding.includeTitle.ivBack.setOnClickListener(this);
        binding.editing.setOnClickListener(this);
        binding.delete.setOnClickListener(this);
        tabAdapter.setOnItemClickListener((adapter, view, position) -> {
            tabAdapter.setSelectIndex(position);
            binding.vpAffiliated.setCurrentItem(position);
        });
        binding.vpAffiliated.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                tabAdapter.setSelectIndex(position);
                ((LinearLayoutManager)binding.rvTab.getLayoutManager()).scrollToPosition(position);
            }
        });
    }
    private void initFragment(AffiliatedFDetailsListEntity listResponse) {
        mFragments.add(AffiliatedFDetailsFragment.newInstance(false,isSelf,motorcadeNo,listResponse.getDriverList()));
        mFragments.add(SelfSupportDetailsFragment.newInstance(true,isSelf,motorcadeNo,listResponse.getCarList()));
        SimpleFragmentAdapter fragmentAdapter = new SimpleFragmentAdapter(this, mFragments);
        binding.vpAffiliated.setAdapter(fragmentAdapter);
        binding.vpAffiliated.setOffscreenPageLimit(mTabs.size());
    }
public void setDetail(AffiliatedFDetailsListEntity listEntity){
        binding.operationBtn.setVisibility(View.VISIBLE);
            if (!isSelf){
                binding.editing.setVisibility(View.GONE);
            }else {
                binding.editing.setVisibility(View.VISIBLE);
            }
        binding.tvFleetDetailsType.setVisibility(isSelf? View.GONE:TextUtils.isEmpty(listEntity.getBusinessType())?View.GONE: View.VISIBLE);
        binding.tvFleetDetailsBusiness.setVisibility(isSelf? View.GONE: TextUtils.isEmpty(listEntity.getMainBusiness())?View.GONE:View.VISIBLE);

        if (isSelf){
            binding.llInfo.setVisibility(View.GONE);
            binding.viewBackgroundWhite.setVisibility(View.GONE);
            binding.tvAffDetailsStateTip.setVisibility(View.GONE);
            Drawable drawable = getResources().getDrawable(R.drawable.icon_self_support);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
            AlignImageSpan centerSpaceImageSpan = new AlignImageSpan(drawable);
            //CenteredImageSpan imgSpan = new CenteredImageSpan(drawable);
            SpannableString spannableString = new SpannableString(StringUtils.toSBC(listEntity.getMotorcadeName().trim()+" "));
            spannableString.setSpan(centerSpaceImageSpan, spannableString.length()-1, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            binding.companyName.setText(spannableString);
        }else {
            Drawable drawable = getResources().getDrawable(R.drawable.icon_affiliated);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
            AlignImageSpan centerSpaceImageSpan = new AlignImageSpan(drawable);
            SpannableString spannableString = new SpannableString(StringUtils.toSBC(listEntity.getMotorcadeName()+" "));
            spannableString.setSpan(centerSpaceImageSpan, spannableString.length()-1, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            binding.companyName.setText(spannableString);
            binding.tvFleetDetailsType.setItemContent(listEntity.getBusinessType());
            binding.tvFleetDetailsBusiness.setItemContent(listEntity.getMainBusiness());
            getState(listEntity,listEntity.getLinkState());
        }
        binding.tvAffDetailsContactsName.setText(listEntity.getContacts());
}
    private void getState(AffiliatedFDetailsListEntity listEntity,String state){
        switch (state){
            case "1":
                binding.tvAffDetailsStateTip.setText("车队已共享"+listEntity.getDriverNum()+"位司机，"+listEntity.getDriverAuthNum()+"辆车供企业调用");
                binding.tvAffDetailsStateName.setTextColor(Color.parseColor("#5792FD"));
                binding.tvAffDetailsStateName.setText("邀请中");
                binding.delete.setText("解除挂靠");
                break;
            case "2":
                binding.tvAffDetailsStateTip.setText("车队管理员已拒绝挂靠");
                binding.tvAffDetailsStateName.setTextColor(Color.parseColor("#FF4B10"));
                binding.tvAffDetailsStateName.setText("已拒绝");
                binding.delete.setText("删除");
                break;
            case "3":
                binding.tvAffDetailsStateTip.setText("车队已共享"+listEntity.getDriverNum()+"位司机，"+listEntity.getDriverAuthNum()+"辆车供企业调用");
                binding.tvAffDetailsStateName.setTextColor(Color.parseColor("#06C764"));
                binding.tvAffDetailsStateName.setText("已同意");
                binding.delete.setText("解除挂靠");
                break;
            case "4":
                /*if (listEntity.getRemoveType()!=null){
                    if (listEntity.getRemoveType()==4){
                        binding.tvAffDetailsStateTip.setText("①企业已解除挂靠关系");
                    }else if (listEntity.getRemoveType()==5){
                        binding.tvAffDetailsStateTip.setText("①车队管理员已解除挂靠关系");
                    }else {
                        binding.tvAffDetailsStateTip.setVisibility(View.GONE);
                    }
                }else {
                    binding.tvAffDetailsStateTip.setVisibility(View.GONE);
                }*/

                binding.tvAffDetailsStateName.setTextColor(Color.parseColor("#969696"));
                binding.tvAffDetailsStateName.setText("已解除");
                binding.delete.setText("删除");
                break;
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateCount(GoodsManageEvent event) {
        //货源管理页面事件
        if (event.getMessageTag() == EventConstant.EVENT_REFRESH_CARGO_MANAGE_TAB_COUNT) {

        } else if (event.getMessageTag() == EventConstant.EVENT_REFRESH_AFFILIATED_SUCCESS) {
           finish();
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(LogisticsEvent event) {
        //解绑/绑定司机，添加/修改车辆信息刷新列表
        if (event.getMessageTag() == EventConstant.EVENT_UNBIND_DRIVER||event.getMessageTag()==EventConstant.EVENT_BIND_DRIVER)
               {
                   viewModel.getAffiliatedFDetails(this,motorcadeNo,isSelf?1:2);
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(MenuEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_REFRESH_PRO_DRIVER) {
            viewModel.getAffiliatedFDetails(this,motorcadeNo,isSelf?1:2);
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_aff_details_im:
                if (!contactsIsInSystem()) {
                    binding.tvAffDetailsIm.setAlpha((float) 0.6);
                    return;
                }
                binding.tvAffDetailsIm.setAlpha((float) 1);
                if (!isLogin()) {
                    VerificationCodeLoginActivity.start(AffiliatedFleetDetailsActivity.this);
                    return;
                }
                if (listResponse != null && !TextUtils.isEmpty(listResponse.getImAccount())) {
                    buildSingleTalking(listResponse.getImAccount());
                }
                break;
            case R.id.tv_aff_details_call:
                if (!isLogin()) {
                    VerificationCodeLoginActivity.start(AffiliatedFleetDetailsActivity.this);
                    return;
                }
                if (listResponse != null && !TextUtils.isEmpty(listResponse.getTelephone())) {
                    new RoundDialog.Builder(getActivity())
                            .title("确认呼叫")
                            .content(listResponse.getTelephone())
                            .confirm("拨打")
                            .cancelable(false)
                            .confirmCallback(view -> {
                                Intent intent = new Intent(Intent.ACTION_DIAL);
                                Uri data = Uri.parse("tel:" + listResponse.getTelephone());
                                intent.setData(data);
                                getActivity().startActivity(intent);
                            })
                            .show();
                } else {
                    ToastUtil.show(this, "未获取到电话号码");
                }
                break;
            case R.id.editing:
                SelfFleetEntity selfFleetEntity = new SelfFleetEntity();
                selfFleetEntity.setMotorcadeNo(motorcadeNo);
                selfFleetEntity.setTelphone(listResponse.getTelephone());
                selfFleetEntity.setName(listResponse.getContacts());
                selfFleetEntity.setMotorcadeName(listResponse.getMotorcadeName());
                selfFleetEntity.setId(listResponse.getId());
                    AddProprietaryFleetActivity.start(this,selfFleetEntity);
                break;
            case R.id.delete:
                if ("解除挂靠".equals(binding.delete.getText())){
                    relation(listResponse);
                }else {showDelDialog(listResponse);
                }
                break;

        }
    }
    /**
     * 删除提示
     */
    private void showDelDialog(AffiliatedFDetailsListEntity data) {
        new RoundDialog.Builder(getActivity())
                .title("温馨提示")
                .content("您确定要删除"+data.getMotorcadeName()+"车队吗？")
                .confirmCallback(v -> viewModel.deleteNo(this, data.getNo()))
                .show();
    }
    /**
     * 解除挂靠提醒
     * @param data
     */
    private void relation(AffiliatedFDetailsListEntity data) {
        new RoundDialog.Builder(getActivity())
                .title("温馨提示")
                .content("挂靠解除后，该挂靠车队共享的司机和车辆将同时被取消共享。您确定要解除挂靠吗？")
                .confirmCallback(v -> viewModel.relation(this, data.getNo()))
                .show();
    }
    /**
     * 同步数据
     */
    private void refreshUIByData(AffiliatedFDetailsListEntity listResponse) {
        if (listResponse == null) {
            MToast.showToast(this,"数据错误");
            return;
        }else {
            this.listResponse = listResponse;
            initFragment(listResponse);
            setDetail(listResponse);
        }
    }
    private boolean contactsIsInSystem() {
        if (listResponse == null ||
                TextUtils.isEmpty(listResponse.getImAccount())) {
            return false;
        }
        return true;
    }
    private boolean isLogin() {
        return !"".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""));
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
